package com.simons.module.cxf.client.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.stereotype.Service;

import com.simons.common.exception.CommonErrorType;
import com.simons.common.exception.CommonException;
import com.simons.module.cxf.client.api.CxfClientConnectService;

import lombok.extern.log4j.Log4j2;

@Log4j2
@Service("cxfClientConnectService")
public class CxfClientConnectServiceImpl implements CxfClientConnectService {

	@Override
	public Client getcxfClientDynamicConnect(String address){
		// 创建动态客户端
		Client client = null;
		try {
			if(StringUtils.isNotBlank(address)){
				JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
				client = dcf.createClient(address);
				log.info("cxf动态客户端，创建成功");
			}
		}
		catch (Exception e) {
			log.error("cxf动态客户端，创建失败", e);
		}
		return client;
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public <T> T getcxfClientProxy(String address, Class<T> clazz) throws CommonException {
		try {
			// 代理工厂
			JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
			// 设置代理地址
			jaxWsProxyFactoryBean.setAddress(address);
			// 设置接口类型
			jaxWsProxyFactoryBean.setServiceClass(clazz);
			// 创建一个代理接口实现
			return (T) jaxWsProxyFactoryBean.create();
		} catch (Exception e) {
			log.error("cxf代理客户端，创建失败", e);
			throw new CommonException(CommonErrorType.COMMON_ERROR,":cxf客户端代理创建失败");
		}
	}
}
